import { FC, useEffect, useState } from "react";
import { observer, inject } from "mobx-react";

import {
  Popover,
  Descriptions,
} from "antd";

import {
  createList,
  ROWWORD,
  computeFontSize,
  coputeBorderWide,
} from "../../utils";

import { ITStore } from "../../store";
import {
  ITShelf,
  ITBottle,
  ITReagent,
  ITDictValue,
  ITFillReagent,
} from "../../store/interfaces";

import "../Shelf/index.less";

interface TProp {
  store: ITStore;
}

interface ITShelfInfo {
  shelf: string;
}

interface ITBPProp extends TProp {
  slotName: string;
  shelfInfo: ITShelfInfo;
}
type TReagentForm = {
  reagentId: string;
  amount?: number;
  defaultAmount: ITFillReagent;
  type?: number;
};

interface ITReagentPopProp extends TProp {
  reagentInfo: ITReagent;
  amount: number;
}



// 试剂信息弹窗
export const ReagentPop: FC<ITReagentPopProp | any> = inject("store")(
  observer(({ store, reagentInfo }: ITReagentPopProp) => {
    const {
      languageStore: { lang, langCur },
      dictionaryStore: { getDictValuesByKey },
    } = store;
    const {
      name,
      cnname,
      formula,
      type,
      density,
      mw,
      structural,
      bp,
      mp,
      abbreviation,
      percentage,
    } = reagentInfo || {};

    const [reagentTypes, setReagentTypes] = useState<ITDictValue[]>([]);

    useEffect(() => {
      setReagentTypes(getDictValuesByKey("reagentFormType"));
      // eslint-disable-next-line react-hooks/exhaustive-deps
    }, []);
    const getReagentLabel = (value: string, _langCur: string) => {
      let label = "";
      reagentTypes.some((item) => {
        if (item.value === value) {
          label = item.label;
          if (_langCur === "zhcn") {
            label = item.cnlabel;
          }
          return true;
        }
        return false;
      });
      return label;
    };

    return (
      <Descriptions bordered size="small" column={2}>
        <Descriptions.Item label={lang["langname"]}>{name}</Descriptions.Item>
        {!!structural && (
          <Descriptions.Item label={lang["langstructuralformula"]}>
            <img src={structural} alt="" width="60" />
          </Descriptions.Item>
        )}
        {!!abbreviation && (
          <Descriptions.Item label={lang["langabbreviation"]}>
            {abbreviation}
          </Descriptions.Item>
        )}
        {!!cnname && (
          <Descriptions.Item label={lang["langcnname"]}>
            {cnname}
          </Descriptions.Item>
        )}
        {!!formula && (
          <Descriptions.Item label={lang["langformula"]}>
            {formula}
          </Descriptions.Item>
        )}
        {!!mw && (
          <Descriptions.Item label={lang["langmolecularweight"]}>
            {mw}
          </Descriptions.Item>
        )}
        {!!mp && (
          <Descriptions.Item label={lang["langmeltingpoint"]}>
            {mp}
          </Descriptions.Item>
        )}
        {!!bp && (
          <Descriptions.Item label={lang["langboilingpoint"]}>
            {bp}
          </Descriptions.Item>
        )}
        {!!density && (
          <Descriptions.Item label={lang["langdensity"]}>
            {density}
          </Descriptions.Item>
        )}
        {!!percentage && (
          <Descriptions.Item label={lang["langpercentage"]}>
            {percentage}
          </Descriptions.Item>
        )}

        <Descriptions.Item label={lang["langtype"]}>
          {getReagentLabel(type, langCur)}
        </Descriptions.Item>
      </Descriptions>
    );
  })
);

const BottlesPlane: FC<ITBPProp | any> = ({
  store,
  shelfInfo,
  slotName,
}: ITBPProp): JSX.Element => {
  const {
    languageStore: { langCur },
    shelfStore: { allShelf },
    globalStore: { mmPixRate },
    bottleStore: { allBottle },
    designerStore: {
      currentReagentsInfo,
      changShowReagentAddEditModal,
      changeReagentAddEditData,
    },
    reagentStore: { getReagentInfoById },
  } = store;

  const { shelf } = shelfInfo;

  const [planeShelf, setPlaneShelf] = useState<ITShelf | null>(null);

  const [planeBottle, setPlaneBottle] = useState<ITBottle | null>(null);

  // 试剂架长度
  const [shelfLength, setShelfLength] = useState<number>(0);

  // 试剂架宽度
  const [shelfWide, setShelfWide] = useState<number>(0);

  // 横向偏移
  const [shelfOffsetx, setShelfOffsetx] = useState<number>(0);

  // 纵向偏移
  const [shelfOffsety, setShelfOffsety] = useState<number>(0);

  // 行数
  const [shelfRow, setShelfRow] = useState<number[]>([]);

  // 列数
  const [shelfColumn, setShelfColumn] = useState<number[]>([]);

  // 行间距
  const [shelfRowSpace, setShelfRowSpace] = useState<number>(0);

  // 列间距
  const [shelfColSpace, setShelfColSpace] = useState<number>(0);

  // 形状
  const [shelfShape, setShelfShape] = useState<string | undefined>(undefined);

  // 直径
  const [shelfDiameter, setShelfDiameter] = useState<number>(0);

  // 瓶子粗细
  const [slotWide, setSlotWide] = useState<number>(4);

  // 瓶子标签字体大小
  const [slotFontSize, setSlotFontSize] = useState<number>(12);

  // 当前试剂盘试剂信息
  const [shelfReagent, setShelfReagent] = useState<any>(null);

  const [hoverBottleName, setHoverBottleName] = useState<string>("");

  useEffect(() => {
    let reagentInfo: any | null = null;
    if (currentReagentsInfo) {
      reagentInfo = currentReagentsInfo[slotName];
    }
    setShelfReagent(reagentInfo);
  }, [currentReagentsInfo, slotName]);

  useEffect(() => {
    setSlotWide(coputeBorderWide(mmPixRate));
  }, [mmPixRate]);

  useEffect(() => {
    let tempShelfInfo = null;

    allShelf.some((item) => {
      if (item.name === shelf) {
        tempShelfInfo = item;
        setPlaneShelf(item);
        return true;
      }
      return false;
    });

    if (tempShelfInfo) {
      const { bottleType } = tempShelfInfo;
      allBottle.some((item) => {
        if (item.id === bottleType) {
          setPlaneBottle(item);
          return true;
        }
        return false;
      });
    }
  }, [allShelf, shelf, allBottle]);

  useEffect(() => {
    if (planeShelf && planeBottle) {
      const {
        length,
        wide,
        row,
        column,
        rowSpace,
        columnSpace,
        offsetx,
        offsety,
      } = planeShelf;
      const { shape, diameter } = planeBottle;

      setShelfLength((length || 0) * mmPixRate);

      setShelfWide((wide || 0) * mmPixRate);

      setShelfOffsetx((offsetx || 0) * mmPixRate);

      setShelfOffsety((offsety || 0) * mmPixRate);

      setShelfRow(createList(row || 0));

      setShelfColumn(createList(column || 0));

      setShelfRowSpace((rowSpace || 0) * mmPixRate);

      setShelfColSpace((columnSpace || 0) * mmPixRate);

      setShelfDiameter((diameter || 0) * mmPixRate);

      setShelfShape(shape);

      setSlotFontSize(computeFontSize(mmPixRate, diameter));
    }
  }, [planeShelf, planeBottle, mmPixRate]);

  const bottleClick = (
    bottleName: string,
    bottleReagentInfo: TReagentForm | null
  ) => {
    changeReagentAddEditData({
      slotName,
      bottleName,
      reagent: bottleReagentInfo,
    });
    changShowReagentAddEditModal(true);
  };

  //   const clearBottleName = () => {
  //     changeReagentAddEditData(null);
  //     changShowReagentAddEditModal(false);
  //   };

  return (
    <>
      <div className="tubeplane">
        {!!shelfLength && !!shelfWide && (
          <div
            className="bord"
            style={{
              paddingLeft: shelfOffsetx,
              paddingTop: shelfOffsety,
              width: shelfLength === 0 ? "auto" : shelfLength,
              height: shelfWide === 0 ? "auto" : shelfWide,
            }}
          >
            {/* 排 */}
            {!!shelfRow.length &&
              shelfRow.map((rowItem) => {
                const rowName = ROWWORD[rowItem];
                return (
                  <div className="row" key={rowItem}>
                    {/* 列 */}
                    {!!shelfColumn.length &&
                      shelfColumn.map((colIndex) => {
                        if (shelfDiameter <= 0) {
                          return null;
                        }

                        const bottleName = rowName + (colIndex + 1);
                        let borderRadius = shelfDiameter;
                        if (shelfShape === "rectangle") {
                          borderRadius = 10;
                        }
                        let bottleReagentInfo: TReagentForm | null = null;
                        // let addAmount: string = "";
                        let reagentInfo = null;
                        let regName: any = "";
                        if (shelfReagent) {
                          bottleReagentInfo = shelfReagent[bottleName];
                          if (bottleReagentInfo) {
                            const { reagentId } = bottleReagentInfo;
                            reagentInfo = getReagentInfoById(reagentId);
                            const { cnname, name } = reagentInfo || {};
                            if (langCur === "zhcn") {
                              regName = cnname;
                            }
                            if (!regName) {
                              regName = name;
                            }

                            // 如果realName太长，截取前10个字符
                            if (regName && regName.length > 10) {
                              regName = regName.slice(0, 10) + "...";
                            }

                            // addAmount = `${tempAmount}${unit}`;
                          }
                        }

                        return (
                          <Popover
                            key={colIndex}
                            title={bottleName}
                            content={<ReagentPop reagentInfo={reagentInfo} />}
                            open={
                              hoverBottleName === bottleName && !!reagentInfo
                            }
                          >
                            <div
                              className={`col ${
                                !!bottleReagentInfo ? "hasreagent" : ""
                              }`}
                              style={{
                                height: shelfDiameter,
                                width: shelfDiameter,
                                borderWidth: slotWide,
                                borderRadius,
                                marginBottom: shelfRowSpace,
                                marginRight: shelfColSpace,
                              }}
                              onClick={() => {
                                bottleClick(bottleName, bottleReagentInfo);
                              }}
                              onMouseEnter={() => {
                                !!bottleReagentInfo &&
                                  setHoverBottleName(bottleName);
                              }}
                              onMouseLeave={() => {
                                setHoverBottleName("");
                              }}
                            >
                              {!bottleReagentInfo && (
                                <div
                                  className="label"
                                  style={{
                                    fontSize: slotFontSize,
                                  }}
                                >
                                  {/* 单个瓶子 */}
                                  {bottleName}
                                </div>
                              )}
                              {!!bottleReagentInfo && (
                                <div className="label hasreagent">
                                  <div>{regName}</div>
                                  {/* <div>{addAmount}</div> */}
                                </div>
                              )}
                            </div>
                          </Popover>
                        );
                      })}
                  </div>
                );
              })}
          </div>
        )}
      </div>
      {/* <ReagentModal close={clearBottleName} /> */}
    </>
  );
};

export default inject("store")(observer(BottlesPlane));
